﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InSys.Alarm
{
    using InSys.Documents;
    public class AlarmObject : IAlarm
    {
        private MapTestLinqDataContext db;

        public AlarmObject()
        {
            db = new MapTestLinqDataContext();
        }

        public bool SetAlarm(int id_user, int id_document, DateTime timemark)
        {
            Alarm alarm = new Alarm();
            bool result = true;
            try
            {
                alarm.id_document = id_document;
                alarm.id_person = id_user;
                alarm.timemark = timemark;
                alarm.active = true;
                db.Alarm.InsertOnSubmit(alarm);
                db.SubmitChanges();
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        public IEnumerable<document> getAlarmedDocuments(int id_user, DateTime timemark)
        {
            var sel_document = from item in db.Alarm where item.active == true && item.id_person==id_user && item.timemark <= timemark select item.id_document;
            IEnumerable<document> result = from item in db.document from sel in sel_document where item.id_document == sel select item;
            return result;
        }

        public bool ClearAlarm(int id_user, int id_document)
        {
            bool result = true;
            try
            {
                IEnumerable<Alarm> list = from item in db.Alarm where item.active == true && item.id_document == id_document && item.id_person == id_user select item;
                foreach (Alarm item in list)
                {
                    item.active = false;
                }
                db.SubmitChanges();
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
    }
}
